﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tesseract;
using System.Drawing;
using System.IO;
using System.Diagnostics;

namespace VstupOcr
{
    class VstupInfoOcr
    {
        private string _fileName;
        private readonly string _outputPath = @"./output/";

        public VstupInfoOcr(string fileName)
        {
            _fileName = fileName;
        }

        public void Recognize()
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            Bitmap source = new Bitmap(_fileName);
            source = ImageUtilities.CropImage(source, 0, 58, source.Width, source.Height - 58 * 2);
            int sourceWidth = source.Width;
            int sourceHeight = source.Height;
            int rateNumber = 0;

            string htmlName = _fileName.Replace("source\\", "");
            string type_id = htmlName;
            string tempPath = "temp/" + htmlName;
            Directory.CreateDirectory(tempPath);
            TextWriter htmlFile = new StreamWriter(string.Format(@"{0}{1}.html", _outputPath, htmlName));

            htmlFile.WriteLine("<!doctype html>");
            htmlFile.WriteLine("<html lang='en'><head><meta charset='utf-8'>");
            htmlFile.WriteLine(string.Format("<title>Розпізнаний текст - {0}</title>", _fileName));
            htmlFile.WriteLine("<style>table, tr, td, th {margin:10px;border:0;padding:10px;}");
            htmlFile.WriteLine("table{border-collapse:collapse;}table td {border: 1px solid black;}td.green {background-color:lightgreen}td.blue {background-color: lightblue}");
            htmlFile.WriteLine("</style>");
            htmlFile.WriteLine("</head>");
            htmlFile.WriteLine("<body>");
            htmlFile.WriteLine("<table>");
            htmlFile.WriteLine("<tr><td>№</td><td>ПІБ</td><td>Бал</td><td>Атестат</td><td>ПК</td><td>ПЧ</td><td>Ц</td><td>Д</td><td>Д(інший напрям)</td></tr>");


            for (int i = 0; i < sourceHeight; i++)
            {
                Color color = source.GetPixel(5, i);
                if (color.Name == "ffdddddd")
                {
                    if (i > 0)
                    {
                        rateNumber++;
                        Bitmap row = ImageUtilities.CropImage(source, 0, i - 58, sourceWidth, 58);
                        int rowWidth = row.Width;
                        int rowHeight = row.Height;

                        int prependX = 0;
                        int cell_id = 0;

                        htmlFile.WriteLine("<tr>");
                        for (int b = 0; b < rowWidth; b++)
                        {
                            Color rowColor = row.GetPixel(b, 5);

                            if (rowColor.Name == "ffdddddd")
                            {
                                if (b > 5)
                                {
                                    int cellX = 0;
                                    int cellWidth = b;
                                    if (prependX != 0)
                                    {
                                        cellX = prependX;
                                    }
                                    else
                                    {
                                        cellX = 0;
                                    }

                                    Bitmap cell = ImageUtilities.CropImage(row, cellX, 0, cellWidth - cellX, rowHeight);
                                    string imageName = tempPath+"/image_" + type_id + "_" + rateNumber + "_" + cell_id + ".jpg";

                                    int zoom = cell_id == 1 ? 12 : 5;
                                    using (var resized = ImageUtilities.ResizeImage(cell, cell.Width * zoom, cell.Height * zoom))
                                    {
                                        ImageUtilities.SaveJpeg(imageName, resized, 100);
                                    }
                                    Color cellColor = cell.GetPixel(2, 2);
                                    string style = "";
                                    if (cellColor.Name == "ffbdd2f0" || cellColor.Name == "ffb4caeb")
                                    {
                                        style = "class='blue'";
                                    }
                                    if (cellColor.Name == "ffa1f8a1" || cellColor.Name == "ff90ee90")
                                    {
                                        style = "class='green'";
                                    }

                                    if (cell_id == 0)
                                    {
                                        htmlFile.WriteLine(string.Format("<td {0}>{1}</td>", style, rateNumber));
                                    }

                                    if (cell_id == 1)
                                    {
                                        
                                        //зар ffbdd2f0 , ffb4caeb
                                        //рек ffa1f8a1 , ff90ee90
                                        string status = "";
                                        if (cellColor.Name == "ffbdd2f0" || cellColor.Name == "ffb4caeb")
                                        {
                                            status += " (зар.)";
                                            style = "class='blue'";
                                        }
                                        if (cellColor.Name == "ffa1f8a1" || cellColor.Name == "ff90ee90")
                                        {
                                            status += " (рек.)";
                                            style = "class='green'";
                                        }

                                        //recognize image
                                        using (var engine = new TesseractEngine(@"./tessdata", "ukr"))
                                        {

                                            using (var img = Pix.LoadFromFile(imageName))
                                            {
                                                using (var page = engine.Process(img))
                                                {
                                                    string text = page.GetText();
                                                    text = text.Replace(" ", ""); ;
                                                    text = text.Replace("\n", " ");
                                                    htmlFile.WriteLine(string.Format("<td {0}>{1}</td>", style, text));
                                                }
                                            }
                                        }

                                    }

                                    if (cell_id == 2 || cell_id == 3)
                                    {

                                        //recognize image
                                        using (var engine = new TesseractEngine(@"./tessdata", "eng", EngineMode.TesseractOnly))
                                        {

                                            engine.DefaultPageSegMode = PageSegMode.SingleLine;
                                            using (var img = Pix.LoadFromFile(imageName))
                                            {
                                                using (var page = engine.Process(img))
                                                {
                                                    string text = page.GetText();
                                                    text = text.Replace(" ", ""); ;
                                                    text = text.Replace("\n", "");
                                                    //file.Write("|" + text);
                                                    htmlFile.WriteLine(string.Format("<td {0}>{1}</td>", style, text));
                                                }
                                            }
                                        }

                                    }

                                    if (cell_id == 7 || cell_id == 8 || cell_id == 9 || cell_id == 10)
                                    {

                                        //recognize image
                                        using (var engine = new TesseractEngine(@"./tessdata", "eng", EngineMode.TesseractOnly))
                                        {
                                            engine.SetVariable("tessedit_char_whitelist", "-+/");
                                            engine.DefaultPageSegMode = PageSegMode.SingleLine;
                                            using (var img = Pix.LoadFromFile(imageName))
                                            {
                                                using (var page = engine.Process(img))
                                                {
                                                    string text = page.GetText();
                                                    text = text.Replace(" ", ""); ;
                                                    text = text.Replace("\n", "");
                                                    string orig = "-";
                                                    string res = "";
                                                    if (text == "V" || text == "+")
                                                    {
                                                        orig = "+";
                                                    }
                                                    htmlFile.WriteLine(string.Format("<td {0}>{1}</td>", style, orig));
                                                    string other_orig = "";
                                                    if (cell_id == 10)
                                                    {
                                                        other_orig = "-";
                                                        if (text == "/+")
                                                        {
                                                            other_orig = "+";
                                                        }
                                                        htmlFile.WriteLine(string.Format("<td {0}>{1}</td>", style, other_orig));

                                                    }
                                                    text = orig + other_orig;
                                                }
                                            }
                                        }

                                    }

                                    prependX = b;
                                    cell_id++;
                                }
                            }
                        }
                    }
                }
            }

            htmlFile.Close();

            Array.ForEach(Directory.GetFiles(tempPath), File.Delete);
            Directory.Delete(tempPath);

            stopwatch.Stop();
            long elapsed_time = stopwatch.ElapsedMilliseconds / 1000;
            Console.WriteLine("Изображение " + htmlName + " распознано " + "(заяв: " + rateNumber +"; " +elapsed_time + "сек.)");  
        }
    }
}
